package com.itheima.service.impl;

import com.itheima.mapper.PermissionMapper;
import com.itheima.mapper.RoleMapper;
import com.itheima.mapper.UserMapper;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Set;

@Service
@Transactional
public class UserServiceImpl implements UserService  {
    @Autowired
    private UserMapper userMapper ;
    @Autowired
    private RoleMapper roleMapper ;
    @Autowired
    private PermissionMapper permissionMapper ;

    //根据用户名来查询用户信息和角色信息 权限
    public User findByUsername(String username) {
        User user = userMapper.findByUsername(username);//用户的基本信息
        if (user == null) {
            return null;
        }
        Integer userid = user.getId();
        //根据用户id查询对应的角色
        Set<Role> roles = roleMapper.findByUserId(userid);
        for (Role role : roles) {
            Integer roleId = role.getId();
            //根据角色id查询对应的权限
            Set<Permission> permissions = permissionMapper.findByRoleId(roleId);
            role.setPermissions(permissions);//角色关联权限
        }
        user.setRoles(roles);//用户关联角色
        return user;
    }
}
